package com.lagou.edu.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author fanbo@imoran.net
 * @date 2020/12/26 10:03
 */
public class XmlConfigBuilder {

    /**
     * 该方法就是使用dom4j对配置文件进行解析，封装Configuration
     * @param path
     * @return
     */
    public void parseConfig(String path) {
        InputStream inputStream = XmlConfigBuilder.class.getClassLoader().getResourceAsStream(path);

        Document document;
        try {
            document = new SAXReader().read(inputStream);
        } catch (DocumentException e) {
            throw new RuntimeException("inputStream-->document过程异常");
        }

        // 获取数据源信息
        Element rootElement = document.getRootElement();
        List propertyList = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Object o : propertyList) {
            Element element = (Element)o;
            String value = element.attributeValue("value");
            String name = element.attributeValue("name");
            properties.setProperty(name,value);
        }
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(properties.getProperty("driverClass"));
        druidDataSource.setUrl(properties.getProperty("jdbcUrl"));
        druidDataSource.setUsername(properties.getProperty("username"));
        druidDataSource.setPassword(properties.getProperty("password"));
        ApplicationConfig.druidDataSource = druidDataSource;

        // 获取注解扫描包路径
        List list = rootElement.selectNodes("//component-scan");
        if(list == null || list.isEmpty()){
            throw new RuntimeException("缺少配置：component-scan");
        }
        Element componentScanElement = (Element)list.get(0);
        ApplicationConfig.basePackage = componentScanElement.attributeValue("base-package");

    }
}
